"ui";
importClass(android.graphics.drawable.GradientDrawable.Orientation);
importClass(android.graphics.drawable.GradientDrawable);
importClass(java.io.FileOutputStream);
importClass(java.net.URL);

var storage = storages.create("baipol");
var androidx = Packages.androidx;
var shape = require("./js/RippleDrawable.js");
var mod = require("modular");
// var Ks = require("script");
var Maple = require('ConSole');
require("./js/SwitchStyle");

//导航颜色
var color = "#3399ff";
//字体颜色
var colog = "#000000";
//状态栏颜色
ui.statusBarColor(color);
if (!files.isDir("/sdcard/百闪pol/")) {
    files.create("/sdcard/百闪pol/");
}
if (!files.isFile("/sdcard/百闪pol/value.json")) {
    files.write("/sdcard/百闪pol/value.json", '');
}
if (!files.isFile("/sdcard/百闪pol/value1.json")) {
    files.write("/sdcard/百闪pol/value1.json", '');
}
var setvalue = files.read("/sdcard/百闪pol/value.json")
var setvalue1 = files.read("/sdcard/百闪pol/value1.json")
let mlkit = require('./MLKitOCR.js');

//requestScreenCapture();
mlkit.init({
    drawFloaty: false,
});
//获取状态栏高度
var StatusBarHeight = context.getResources().getDimensionPixelSize(context.getResources().getIdentifier("status_bar_height", "dimen", "android"))
//一直保持屏幕常亮
device.keepScreenOn();
$ui.layout(
    <drawer id="drawer">
        <vertical  id="MainUIColor">
            {/***标题栏***/}
            <appbar>
                <toolbar bg="{{color}}" title="百闪pol" id="toolbar"/>
            </appbar>
            <viewpager id="viewPager" layout_alignParentBottom="true" layout_weight="1">
                {/***页面1***/}
                <frame id="home">
                    <ScrollView>
                        <vertical padding="10">
                            
                            <Switch-layout id="guolu" text="是否启用过滤精灵编号" h="auto" textSize="18sp" trackColors="#FFFFFF|#9E9E9E" node="轨道背景颜色参数 未选中|选中" trackStroke="1|#A6A6A6|#FFFFFFFF" node="轨道边框参数 宽度|未选中颜色|选中颜色"/>
                            <vertical id="glst">
                                <input text="{{setvalue}}" hint="编号" padding="5" marginBottom="10" gravity="top" lines="8" id="wb1" w="*" />
                                <button id="bcsz" text="保存设置"/>
                            </vertical>
                            <Switch-layout id="choice" text="是否启用选择精灵编号" h="auto" textSize="18sp" trackColors="#FFFFFF|#9E9E9E" node="轨道背景颜色参数 未选中|选中" trackStroke="1|#A6A6A6|#FFFFFFFF" node="轨道边框参数 宽度|未选中颜色|选中颜色"/>
                            <vertical id="xzbh">
                                <input text="{{setvalue1}}" hint="编号" padding="5" marginBottom="10" gravity="top" lines="8" id="wb2" w="*" />
                                <button id="bcsz1" text="保存设置"/>
                            </vertical>
                            <horizontal>
                                <Switch-layout layout_weight="1" id="cd" text="清除精灵CD记录" h="auto" textSize="18sp" trackColors="#FFFFFF|#9E9E9E" node="轨道背景颜色参数 未选中|选中" trackStroke="1|#A6A6A6|#FFFFFFFF" node="轨道边框参数 宽度|未选中颜色|选中颜色"/>
                            </horizontal>
                            <Switch-layout id="cdkg" text="是否启用CD时间" h="auto" textSize="18sp" trackColors="#FFFFFF|#9E9E9E" node="轨道背景颜色参数 未选中|选中" trackStroke="1|#A6A6A6|#FFFFFFFF" node="轨道边框参数 宽度|未选中颜色|选中颜色"/>
                            <vertical id="cdst">
                                <input hint="已等待时间/分钟" padding="5" marginBottom="10" gravity="top" lines="1" id="wb3" w="*" />
                            </vertical>
                            <Switch-layout id="vibration" text="振动" h="auto" textSize="18sp" trackColors="#FFFFFF|#9E9E9E" node="轨道背景颜色参数 未选中|选中" trackStroke="1|#A6A6A6|#FFFFFFFF" node="轨道边框参数 宽度|未选中颜色|选中颜色"/>
                            <Switch-layout id="Partaking" text="游戏分身" h="auto" textSize="18sp" trackColors="#FFFFFF|#9E9E9E" node="轨道背景颜色参数 未选中|选中" trackStroke="1|#A6A6A6|#FFFFFFFF" node="轨道边框参数 宽度|未选中颜色|选中颜色"/>
                            
                            <horizontal>
                                <text text="中心偏移："/>
                                <input layout_weight="1" padding="5" marginBottom="10" id="Offset" hint='中心点偏移值'/>
                            </horizontal>
                            <horizontal>
                                <text text="等待时间："/>
                                <input layout_weight="1" padding="5" marginBottom="10" id="Time" hint='传送过后等待时间'/>
                            </horizontal>
                            <horizontal>
                                <text text="中心坐标："/>
                                <input layout_weight="1" padding="5" marginBottom="10" id="zhong" hint='中心点坐标'/>
                            </horizontal>
                            <button id="an" marginBottom="30dp" text="运行"/>
                            
                        </vertical>
                    </ScrollView>
                </frame>
                <frame id="notifications">
                    <ScrollView style="overflow-x:hidden" >
                        <vertical>
                            <vertical padding="12">
                                <horizontal id="anzh" padding="10" >
                                    <img id="tx" layout_gravity="center"
                                    w="50" h="50" scaleType="fitXY" circle="true"/>
                                    <vertical id="PersonalData" >
                                        <text layout_weight="1" marginLeft="15" textStyle="bold"   textColor="#000000" gravity="center|left" h="*" id="Names" text="昵称"  />
                                        <text layout_weight="1" marginLeft="15" id="introduction" text="个性签名" />
                                        <text layout_weight="1" marginLeft="15" textStyle="bold"   textColor="#AA66CC" gravity="center|left" h="*" id="vipname" text="未开通会员" />
                                        <text layout_weight="1" marginLeft="15" textStyle="bold"   textColor="#AA66CC" gravity="center|left" h="*" id="viptime" />
                                    </vertical>
                                </horizontal>
                                <linear>
                                    <button layout_weight="1" margin="5" id="kami"   w="*" h="auto" text="开通会员" />
                                    <button layout_weight="1" margin="5" id="xgmm"   w="*" h="auto" text="修改密码" />
                                    <button layout_weight="1" margin="5" id="tcdl"   w="*" h="auto" text="退出登录" />
                                    
                                </linear>
                            </vertical>
                            <vertical padding="10">
                                <text text="权限服务" marginLeft="12dp" textSize="18sp" textColor="#2196F3"/>
                                <Switch-layout id="autoService" text="无障碍服务" h="auto" checked="{{auto.service != null}}" textSize="18sp" trackColors="#FFFFFF|#9E9E9E" node="轨道背景颜色参数 未选中|选中" trackStroke="1|#A6A6A6|#FFFFFFFF" node="轨道边框参数 宽度|未选中颜色|选中颜色"/>
                                <Switch-layout id="floatyService" text="悬浮窗权限" h="auto" checked="{{(new android.provider.Settings).canDrawOverlays(context)}}" textSize="18sp" trackColors="#FFFFFF|#9E9E9E" node="轨道背景颜色参数 未选中|选中" trackStroke="1|#A6A6A6|#FFFFFFFF" node="轨道边框参数 宽度|未选中颜色|选中颜色"/>
                                <Switch-layout id="journal" text="日志悬浮窗" h="auto" textSize="18sp" trackColors="#FFFFFF|#9E9E9E" node="轨道背景颜色参数 未选中|选中" trackStroke="1|#A6A6A6|#FFFFFFFF" node="轨道边框参数 宽度|未选中颜色|选中颜色"/>
                                
                                
                            </vertical>
                        </vertical>
                    </ScrollView>
                </frame>
            </viewpager>
            {/***底部框架***/}
            <bottomnaviagtion id="navigation" bg="#ffffff" />
        </vertical>
        {/***侧滑栏***/}
        <vertical layout_gravity="left" bg="#ffffff" w="280">
            <img w="280" h="200" scaleType="fitXY" src="http://images.shejidaren.com/wp-content/uploads/2014/10/023746fki.jpg"/>
            <list id="menu">
                <horizontal bg="?selectableItemBackground" w="*">
                    <img w="50" h="50" padding="16" tint="#42a5f5" src="{{this.icon}}" />
                    <text textColor="black" textSize="15sp" text="{{this.title}}" layout_gravity="center"/>
                </horizontal>
            </list>
        </vertical>
    </drawer>
);

mod.ShapeButton(ui.an);
mod.ShapeButton(ui.bcsz);
mod.ShapeButton(ui.bcsz1);
mod.ShapeButton(ui.kami);
mod.ShapeButton(ui.xgmm);
mod.ShapeButton(ui.tcdl);


mod.ShapeInput(ui.wb1);
mod.ShapeInput(ui.wb2);
mod.ShapeInput(ui.wb3);
//mod.ShapeInput(ui.wb4);
mod.ShapeInput(ui.zhong);
mod.ShapeInput(ui.Time);
mod.ShapeInput(ui.Offset);
// 设置底部导航栏的内容
let menuItems = [];
let menu = ui.navigation.menu;
menuItems.push(buildMenuItem(menu, '首页', ui.R.drawable.ic_home_black_48dp));
//menuItems.push(buildMenuItem(menu, '发现', ui.R.drawable.ic_dashboard_black_48dp));
menuItems.push(buildMenuItem(menu, '我的', ui.R.drawable.ic_person_black_48dp));
// 当底部按钮被选中时，切换ViewPager页面为相应位置的页面
$ui.navigation.setOnNavigationItemSelectedListener(function(item) {
    ui.viewPager.currentItem = menuItems.indexOf(item);
    return true;
});
// 当ViewPager页面切换时，切换底部按钮的状态
$ui.viewPager.addOnPageChangeListener(new androidx.viewpager.widget.ViewPager.OnPageChangeListener({
    onPageSelected: function(position) {
        menuItems[position].setChecked(true);
    }
}));

function buildMenuItem(menu, title, icon) {
    let menuItem = menu.add(title);
    menuItem.setIcon(icon);
    return menuItem;
}

$ui.emitter.on("create_options_menu", menu => {
    menu.add("设置");
    menu.add("日志");
    menu.add("更新日志");
    menu.add("点击获取坐标(root)");
    menu.add("点击获取坐标");
    menu.add("截取图片获取坐标");


});
$ui.emitter.on("options_item_selected", (e, item) => {
    switch (item.getTitle()) {
        case "设置":
            app.startActivity("settings");
            break;
        case "日志":
            app.startActivity("console");
            break;
        case "更新日志":
            mod.更新日志();
            break;
        case "点击获取坐标(root)":
            悬浮("./指针位置.js")
            break;
        case "点击获取坐标":
            悬浮("./点击获取坐标.js")
            break;
        case "截取图片获取坐标":
            悬浮("./截图获取坐标.js")
            break;
    }
});
activity.setSupportActionBar(ui.toolbar);
let lastPressedTime = 0;
ui.emitter.on("back_pressed", (e) => {
    let time = Date.now();
    if (time - lastPressedTime < 1000) {
        return;
    }
    toast("再按一次退出程序");
    e.consumed = true;
    lastPressedTime = time;
});

ui.xgmm.on("click", function() {
    mod.修改密码();
});
ui.kami.on("click", function() {
    mod.使用卡密();
});
ui.PersonalData.on("click", function() {
    mod.直接修改用户信息();
});
//上传头像
ui.tx.on("click", function() {
    mod.startChooseFile("*/*");
});
ui.tcdl.on("click", function() {
    storage.remove("username");
    storage.remove("usertoken");
    engines.stopAll();
    engines.execScriptFile("main.js");
});
threads.start(function() {
    try {
        //下载对话框
        mod.获取更新();
        //对话框公告
        mod.获取公告();
        //用户信息
        mod.用户信息();
    } catch (e) {
        toast("请检查网络!!");
    }
})


if (storage.get("Time")) {
    ui.Time.attr("text", storage.get("Time"));
}
if (storage.get("zhong")) {
    ui.zhong.attr("text", storage.get("zhong"));
}
if (storage.get("Offset")) {
    ui.Offset.attr("text", storage.get("Offset"));
}
//无障碍悬浮窗//
//无障碍
ui.autoService.on("check", function(checked) {
    if (checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        })
    }
    if (!checked && auto.service != null) {
        auto.service.disableSelf()
    }
})
//悬浮窗
ui.floatyService.on("check", function() {
    try {
        app.startActivity({
            packageName: "com.android.settings",
            className: "com.android.settings.Settings$AppDrawOverlaySettingsActivity",
            data: "package:" + context.getPackageName()
        });

    } catch (error) {
        app.startActivity({
            action: "android.settings.action.MANAGE_OVERLAY_PERMISSION"
        })
    }
});

ui.emitter.on("resume", function() {
    //无障碍同步开关状态
    ui.autoService.checked = auto.service != null
    //悬浮窗同步开关状态
    ui.floatyService.checked = (new android.provider.Settings).canDrawOverlays(context)
});

//日志
ui.journal.on("check", (checked) => {
    if (checked) {
        // threads.start(function() {
        Maple.ConSole();
        //  })
        storage.put("日志", "true");
    } else {
        floaty.closeAll()
        storage.put("日志", "false");
    }
});

if (storage.get("日志")) {
    if (storage.get("日志") == "true") {
        ui.journal.setChecked(true);
    } else if (storage.get("日志") == "false") {
        ui.journal.setChecked(false);
    }
}
//游戏分身
ui.Partaking.on("check", (checked) => {
    if (checked) {
        storage.put("Partaking", true);
        //  ui.king.setVisibility(0);
    } else {
        storage.put("Partaking", false);
        //  ui.king.setVisibility(8);
    }
});
if (storage.get("Partaking")) {
    ui.Partaking.setChecked(storage.get("Partaking"));
}

// if (ui.Partaking.isChecked()) {
//     ui.king.setVisibility(0);
// } else {
//     ui.king.setVisibility(8);
// }
// if (storage.get("wb4")) {
//     ui.wb4.attr("text", storage.get("wb4"));
// }



//振动
ui.vibration.on("check", (checked) => {
    if (checked) {
        storage.put("vibration", true);
        ui.vibration.attr("text", "震动已开启");
    } else {
        storage.put("vibration", false);
        ui.vibration.attr("text", "震动已关闭");
    }
});
if (storage.get("vibration")) {
    ui.vibration.setChecked(storage.get("vibration"));
    ui.vibration.attr("text", "震动已开启");
} else {
    ui.vibration.attr("text", "震动已关闭");
}

//清除精灵CD记录
ui.cd.on("check", (checked) => {
    if (checked) {
        storage.put("cd", true);
    } else {
        storage.put("cd", false);
    }
});
if (storage.get("cd")) {
    ui.cd.setChecked(storage.get("cd"));
}
//cd开关
ui.cdkg.on("check", (checked) => {
    if (checked) {
        storage.put("cdkg", true);
        ui.cdst.setVisibility(0);
    } else {
        storage.put("cdkg", false);
        ui.cdst.setVisibility(8);
    }
});
if (ui.cdkg.isChecked() == true) {
    ui.cdst.setVisibility(0);
} else {
    ui.cdst.setVisibility(8);
}
if (storage.get("cdkg")) {
    ui.cdkg.setChecked(storage.get("cdkg"));
}
if (storage.get("wb3")) {
    ui.wb3.attr("text", storage.get("wb3"))
}
//是否启用过滤精灵编号

ui.guolu.on("check", (checked) => {
    if (checked) {
        storage.put("guolu", true);
        ui.glst.setVisibility(0);
    } else {
        storage.put("guolu", false);
        ui.glst.setVisibility(8);
    }
});

if (ui.guolu.isChecked() == true) {
    ui.glst.setVisibility(0);
} else {
    ui.glst.setVisibility(8);
}
if (storage.get("guolu")) {
    ui.guolu.setChecked(storage.get("guolu"));
}

//是否启用选择精灵编号
ui.choice.on("check", (checked) => {
    if (checked) {
        storage.put("choice", true);
        ui.xzbh.setVisibility(0);
    } else {
        storage.put("choice", false);
        ui.xzbh.setVisibility(8);
    }
});

if (ui.choice.isChecked() == true) {
    ui.xzbh.setVisibility(0);
} else {
    ui.xzbh.setVisibility(8);
}
if (storage.get("choice")) {
    ui.choice.setChecked(storage.get("choice"));
}

//运行
ui.an.on("click", function() {
    threads.start(function() {
        if (auto.service == null) {
            toast("右上角设置开启无障碍")
            return;
        }
        if (ui.zhong.attr("text") == "") {
            toast("请输入要点击的中心坐标");
            return;
        }
        if (ui.Time.attr("text") == "") {
            toast("请输入等待时间");
            return;
        }
        if (ui.Offset.attr("text") == "") {
            toast("请输入偏移值");
            return;
        }
        if (ui.cdkg.isChecked() == true) {
            if (ui.wb3.attr("text") == "") {
                toast("启用CD时间必须输入已等待时间");
                return;
            }
        }
        if (ui.guolu.isChecked() == true) {
            let vs = ui.wb1.attr("text");
            if (vs == "") {
                toast("启用过滤必须输入要过滤的编号");
                return;
            }
        }
        if (ui.choice.isChecked() == true) {
            let vs1 = ui.wb2.attr("text");
            if (vs1 == "") {
                toast("启用选择必须输入要过滤的编号");
                return;
            }
        }
        if (ui.choice.isChecked() == true && ui.guolu.isChecked() == true) {
            toastLog("过滤单选只能选择一个,否则冲突")
            return;
        }

        if (ui.cd.isChecked() == true) {
            storage.remove("Coords");
        }
        if (ui.cdkg.isChecked() == true) {
            storage.put("wb3", ui.wb3.attr("text"));
        }
        //中心坐标
        storage.put("zhong", ui.zhong.attr("text"));
        storage.put("Time", ui.Time.attr("text"));
        storage.put("Offset", ui.Offset.attr("text"));
        if (ui.choice.isChecked() == true) {
            let getwb = ui.wb2.attr("text").split(",");

            var url = "http://47.243.176.108:62/apipro/isVip";
            ret = http.post(url, {
                "appid": "10003",
                "username": storage.get("username"),
            }, {
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                    "User-Agent": "Mozilla/5.0 (Linux; Android 6.0.1; OPPO R9s Plus Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36"
                }
            });
            var res = ret.body.json();
            if (res.code == 200) {
                var a = $crypto.digest("social" + res.msg, "MD5");
                if (a == res.data) {
                    if (res.msg == "true") {
                        start1(getwb);
                    } else {
                        toastLog("您还不是会员");
                        return;
                    }
                } else {
                    // toast("抓包还想进来？");
                    return;
                }
            } else {
                toastLog("您还不是会员");
                return;
            }
        } else {
            var url = "http://47.243.176.108:62/apipro/isVip";
            ret = http.post(url, {
                "appid": "10003",
                "username": storage.get("username"),
            }, {
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                    "User-Agent": "Mozilla/5.0 (Linux; Android 6.0.1; OPPO R9s Plus Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36"
                }
            });
            var res = ret.body.json();
            if (res.code == 200) {
                var a = $crypto.digest("social" + res.msg, "MD5");
                if (a == res.data) {
                    if (res.msg == "true") {
                        start();
                    } else {
                        toastLog("您还不是会员");
                        return;
                    }
                } else {
                    // toast("抓包还想进来？");
                    return;
                }
            } else {
                toastLog("您还不是会员");
                return;
            }
        }

    });
});

ui.bcsz.on("click", function() {
    let getwb = ui.wb1.attr("text");
    if (getwb == "") {
        toast("数值参数未设置");
        return;
    }
    files.write("/sdcard/百闪pol/value.json", getwb);
    toast("已保存");
});

ui.bcsz1.on("click", function() {
    let getwb = ui.wb2.attr("text");
    if (getwb == "") {
        toast("数值参数未设置");
        return;
    }
    files.write("/sdcard/百闪pol/value1.json", getwb);
    toast("已保存");
});

function 悬浮(path) {
    // 检查悬浮窗权限
    if (!$floaty.checkPermission()) {
        requestForFloatingPermission();
        return;
    }
    // 启用悬浮控制条，控制脚本worker.js
    $engines.startFloatingController(path);

}

function requestForFloatingPermission() {
    // 设置为显示应用内对话框
    $dialogs.setDefaultDialogType('app');
    // 弹出权限确认框
    $dialogs.confirm("权限申请", "需要悬浮窗权限来展示控制条，请在设置界面允许在其他应用上层显示")
        .then(ok => {
            if (ok) {
                $floaty.requestPermission();
            }
        });
}

events.on("exit", function() {
    storage.put("EndTimes1", new Date().getTime())
});








function start() {
    threads.start(function() {
        ImgAuthority();
        if (!files.isDir("/sdcard/百闪pol")) {
            files.create("/sdcard/百闪pol/");
        }

        //    if (!files.isFile("/sdcard/百闪pol/list.json")) {
        while (true) {
            try {
                threads.start(function() {
                    请求数据();
                }).join();
                break;
            } catch (e) {
                log("请求数据失败,请检查网络!");
            }
            log("暂停一分钟继续请求");
            sleep(60000);
        }
        // }
        while (true) {
            let fie = JSON.parse(files.read("/sdcard/百闪pol/list.json"));
            if (!fie.length) {
                log("检测到本地没有数据,正在尝试重新获取数据")
                请求数据();
                sleep(1000);
            } else {
                break;
            }
            log("30秒后继续请求");
            sleep(30 * 1000);
        }
        log("打开游戏");
        app.launchPackage("com.nianticlabs.pokemongo");

        if (storage.get("Partaking")) {
            textMatches("Pokémon GO").findOne()
            sleep(1000);
            textMatches("Pokémon GO").findOne().clickCenter();
            sleep(500);
            while (true) {
                if (textMatches("Pokémon GO").exists()) {
                    textMatches("Pokémon GO").findOne().clickCenter();
                } else {
                    break;
                }
                sleep(500);
            }
        }
        log("等待游戏出现");
        等待游戏出现();
        log("3秒后拉远视角");
        sleep(3000);
        拉远视角();
        sleep(1000);
        if (!storage.get("j")) {
            storage.put("j", 0);
        }
        storage.put("startTime", new Date().getTime());
        while (true) {
            if (new Date().getTime() - storage.get("startTime") >= 20 * 60 * 1000) {
                重启();
                storage.put("startTime", new Date().getTime());
            }
            while (true) {
                if (storage.get("nums") <= storage.get("j")) {
                    while (true) {
                        try {
                            // threads.start(function() {
                            请求数据();
                            // }).join();
                            break;
                        } catch (e) {
                            log("请求数据失败,请检查网络!");
                        }
                        log("暂停一分钟继续请求");
                        sleep(60000);
                    }
                }
                while (true) {
                    let fie = JSON.parse(files.read("/sdcard/百闪pol/list.json"));
                    if (!fie[storage.get("j")]) {
                        请求数据();
                        sleep(1000);
                    } else {
                        break;
                    }
                }
                sleep(1000);
                let obj = JSON.parse(files.read("/sdcard/百闪pol/list.json"));
                let st = (new Date(obj[parseInt(storage.get("j"))].EndTime.replace(/-/g, "/"))).getTime() / 1000;
                if (ui.guolu.isChecked() == true) {
                    if (st <= ent() || guolu(obj)) {
                        //过滤
                        storage.put("j", storage.get("j") + 1);
                    } else {
                        //继续
                        break;
                    }
                } else {
                    if (st <= ent()) {
                        //过滤
                        storage.put("j", storage.get("j") + 1);
                    } else {
                        //继续
                        break;
                    }
                }

            }
            sleep(1000);
            var obj = JSON.parse(files.read("/sdcard/百闪pol/list.json"));
            var s = storage.get("j");
            //setClip(obj[s].Coords);
            log("坐标:" + obj[s].Coords);
            sleep(100);
            log("精灵:" + obj[s].title);
            sleep(100);
            log("结束时间:" + obj[s].EndTime);
            sleep(100);
            log("等级:" + obj[s].iv);
            Joy传送(obj[s].Coords);
            storage.put("j", s + 1);
            log("等待" + storage.get("Time") + "秒");
            sleep(storage.get("Time") * 1000);
            天气识别();
            if (判断紫色()) {
                if (storage.get("vibration") == true) {
                    device.vibrate(5000);
                }
                if (storage.get("Coords")) {
                    for (var i1 = 0; i1 < 15; i1++) {
                        点击中心点();
                        let r = mlkit.findText(/15\/15\/15|100%/, 1000, [0, StatusBarHeight, device.width, device.height]);
                        if (r.length) {
                            let r1 = r.filter(i => /15\/15\/15/.test(i.text));
                            let r2 = r.filter(i => /100%/.test(i.text));
                            if (r1.length && r2.length) {
                                
                                var ST = storage.get("Coords");
                                var ET = obj[s].Coords;
                                var StartTime = ST.split(",");
                                var EndTime = ET.split(",");
                                var a = getDistances(StartTime[0], StartTime[1], EndTime[0], EndTime[1]);
                                var vti = new Date().getTime() - storage.get("abs");
                                if (storage.get("EndTimes1")) {
                                    vti = (new Date().getTime() - storage.get("EndTimes1")) + vti;
                                    storage.remove("EndTimes1");
                                }
                                
                                if (ui.cdkg.isChecked() == true) {
                                    var times = (a.distance * 48 * 1000 - vti) - (storage.get("wb3") * 60 * 1000);
                                } else {
                                    var times = a.distance * 48 * 1000 - vti;
                                }
                                
                                if (times.toString().indexOf("-") == -1) {
                                    if (times >= 7200000) {
                                        //  log("等待2个小时");
                                        for (var i = 7200; i--;) {
                                            sleep(1000);
                                            log("等待时间还剩" + i + "秒");
                                        }
                                    } else {
                                        // log("等待" + times / 1000 + "秒");
                                        // sleep(times);
                                        for (var j = parseInt(times / 1000); j--;) {
                                            sleep(1000);
                                            log("等待时间还剩" + j + "秒");
                                        }
                                    }
                                }
                                天气识别();
                                自动捕捉();
                                天气识别();
                                storage.put("Coords", obj[s].Coords);
                                storage.put("abs", new Date().getTime());
                                重启();
                                break;
                            } else {
                                sleep(100)
                                back();
                            }
                        } else {
                            sleep(100);
                            back();
                        }
                    }
                } else {
                    for (var i2 = 0; i2 < 15; i2++) {

                        点击中心点();
                        let r = mlkit.findText(/15\/15\/15|100%/, 1000, [0, StatusBarHeight, device.width, device.height]);
                        if (r.length) {
                            let r1 = r.filter(i => /15\/15\/15/.test(i.text));
                            let r2 = r.filter(i => /100%/.test(i.text));
                            if (r1.length && r2.length) {
                                天气识别();
                                自动捕捉();
                                天气识别();
                                storage.put("Coords", obj[s].Coords);
                                storage.put("abs", new Date().getTime());
                                重启();
                                break;
                            } else {
                                sleep(100)
                                back();
                            }
                        } else {
                            sleep(100);
                            back();
                        }
                    }
                }
            }
            sleep(1000);

        }
    });


}

function start1(str) {
    threads.start(function() {
        ImgAuthority();
        if (!files.isDir("/sdcard/百闪pol")) {
            files.create("/sdcard/百闪pol/");
        }

        // if (!files.isFile("/sdcard/百闪pol/list.json")) {
        while (true) {
            try {
                //    threads.start(function() {
                请求数据1(str);
                //  }).join();
                break;
            } catch (e) {
                log("请求数据失败,请检查网络!");
            }
            log("暂停一分钟继续请求");
            sleep(60000);
        }
        //}
        while (true) {
            let fie = JSON.parse(files.read("/sdcard/百闪pol/list.json"));
            if (!fie.length) {
                log("检测到本地没有数据,正在尝试重新获取数据")
                请求数据1(str);
                sleep(1000);
            } else {
                break;
            }
            log("30秒后继续请求");
            sleep(30 * 1000);
        }
        log("打开游戏");
        app.launchPackage("com.nianticlabs.pokemongo");

        if (storage.get("Partaking")) {
            textMatches("Pokémon GO").findOne()
            sleep(1000);
            textMatches("Pokémon GO").findOne().clickCenter();
            sleep(500);
            while (true) {
                if (textMatches("Pokémon GO").exists()) {
                    textMatches("Pokémon GO").findOne().clickCenter();
                } else {
                    break;
                }
                sleep(500);
            }
        }
        log("等待游戏出现");
        等待游戏出现();
        log("3秒后拉远视角");
        sleep(3000);
        拉远视角();
        sleep(1000);
        if (!storage.get("j")) {
            storage.put("j", 0);
        }
        storage.put("startTime", new Date().getTime());
        while (true) {
            if (new Date().getTime() - storage.get("startTime") >= 20 * 60 * 1000) {
                重启();
                storage.put("startTime", new Date().getTime());
            }
            while (true) {
                if (storage.get("nums") <= storage.get("j")) {
                    while (true) {
                        try {
                            //        threads.start(function() {
                            请求数据1(str);
                            //    }).join();
                            break;
                        } catch (e) {
                            log("请求数据失败,请检查网络!");
                        }
                        log("暂停一分钟继续请求");
                        sleep(60000);
                    }
                }
                while (true) {
                    let fie = JSON.parse(files.read("/sdcard/百闪pol/list.json"));
                    if (!fie[storage.get("j")]) {
                        请求数据1(str);
                        sleep(1000);
                    } else {
                        break;
                    }
                }
                sleep(1000);
                let obj = JSON.parse(files.read("/sdcard/百闪pol/list.json"));
                let st = (new Date(obj[parseInt(storage.get("j"))].EndTime.replace(/-/g, "/"))).getTime() / 1000;
                if (st <= ent()) {
                    //过滤
                    storage.put("j", storage.get("j") + 1);
                } else {
                    //继续
                    break;
                }

            }
            sleep(1000);
            var obj = JSON.parse(files.read("/sdcard/百闪pol/list.json"));
            var s = storage.get("j");
            //setClip(obj[s].Coords);
            log("坐标:" + obj[s].Coords);
            sleep(100);
            log("精灵:" + obj[s].title);
            sleep(100);
            log("结束时间:" + obj[s].EndTime);
            sleep(100);
            log("等级:" + obj[s].iv);
            Joy传送(obj[s].Coords);
            storage.put("j", s + 1);
            log("等待" + storage.get("Time") + "秒");
            sleep(storage.get("Time") * 1000);
            天气识别();
            if (判断紫色()) {
                if (storage.get("vibration") == true) {
                    device.vibrate(5000);
                }
                if (storage.get("Coords")) {
                    for (var i1 = 0; i1 < 15; i1++) {
                        点击中心点();
                        let r = mlkit.findText(/15\/15\/15|100%/, 1000, [0, StatusBarHeight, device.width, device.height]);
                        if (r.length) {
                            let r1 = r.filter(i => /15\/15\/15/.test(i.text));
                            let r2 = r.filter(i => /100%/.test(i.text));
                            if (r1.length && r2.length) {
                                //判断值
                                var ST = storage.get("Coords");
                                var ET = obj[s].Coords;
                                var StartTime = ST.split(",");
                                var EndTime = ET.split(",");
                                var a = getDistances(StartTime[0], StartTime[1], EndTime[0], EndTime[1]);

                                var vti = new Date().getTime() - storage.get("abs");
                                if (storage.get("EndTimes1")) {
                                    vti = (new Date().getTime() - storage.get("EndTimes1")) + vti;
                                    storage.remove("EndTimes1");
                                }
                                if (ui.cdkg.isChecked() == true) {
                                    var times = (a.distance * 48 * 1000 - vti) - (storage.get("wb3") * 60 * 1000);
                                } else {
                                    var times = a.distance * 48 * 1000 - vti;
                                }
                                log(times);
                                if (times.toString().indexOf("-") == -1) {
                                    if (times >= 7200000) {
                                        //log("等待2个小时");
                                        for (var i = 7200; i--;) {
                                            sleep(1000);
                                            log("等待时间还剩" + i + "秒");
                                        }
                                    } else {
                                        // log("等待" + times / 1000 + "秒");
                                        // sleep(times);
                                        for (var j = parseInt(times / 1000); j--;) {
                                            sleep(1000);
                                            log("等待时间还剩" + j + "秒");
                                        }
                                    }
                                }
                                天气识别();
                                自动捕捉();
                                天气识别();
                                storage.put("Coords", obj[s].Coords);
                                storage.put("abs", new Date().getTime());
                                重启();
                                break;
                            } else {
                                sleep(100)
                                back();
                            }
                        } else {
                            sleep(100);
                            back();
                        }
                    }
                } else {
                    for (var i2 = 0; i2 < 15; i2++) {

                        点击中心点();
                        let r = mlkit.findText(/15\/15\/15|100%/, 1000, [0, StatusBarHeight, device.width, device.height]);
                        if (r.length) {
                            let r1 = r.filter(i => /15\/15\/15/.test(i.text));
                            let r2 = r.filter(i => /100%/.test(i.text));
                            if (r1.length && r2.length) {
                                天气识别();
                                自动捕捉();
                                天气识别();
                                storage.put("Coords", obj[s].Coords);
                                storage.put("abs", new Date().getTime());
                                重启();
                                break;
                            } else {
                                sleep(100)
                                back();
                            }
                        } else {
                            sleep(100);
                            back();
                        }
                    }
                }
            }
            sleep(1000);

        }
    });


}
/*
判断值15/15/15 百分比100% 闪光 同时满足就抓
    
时间计算 开关功能 点运行 是否清除上次的记录坐标
    
日志悬浮窗
    
识别区域尽量识别区域
    
紫色头 限制图片范围测试颜色 
    
要抓的精灵多选
*/

function 天气识别() {
    let r = mlkit.findText(/我不是駕駛|我不是|駕駛|已確認安全|確認|已確認|確認安全|確認安|認安全/, 1000, [0, StatusBarHeight, device.width, device.height]);
    if (r.length) {
        mlkit.clickResult(r);
    }
}

function 重启() {
    log("执行退出游戏");
    sleep(100);
    back();
    while (true) {
        let r = mlkit.findText(/OK|取消|結束/, 1000, [0, StatusBarHeight, device.width, device.height]);
        let r1 = r.filter(i => /OK/.test(i.text));
        if (r1.length) {
            mlkit.clickResult(r1);
            break;
        }
        let r2 = r.filter(i => /取消/.test(i.text));
        if (r2.length) {
            mlkit.clickResult(r2, {
                offsetY: -(r2[0].bounds.height() * 4)
            });
            break;
        }
        let r3 = r.filter(i => /結束/.test(i.text));
        if (r3.length) {
            mlkit.clickResult(r3, {
                offsetY: +(r3[0].bounds.height() * 4)
            });
            break;
        }
        sleep(500);
        back();
        sleep(500);
    }
    sleep(1000);
    while (true) {
        //  setTimeout(function() {
        toastLog("回到主界面");
        i = new Intent(context, activity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(i);
        //  }, 1000);
        sleep(1000);
        log("打开游戏");
        app.launchPackage("com.evermorelabs.polygonsharp");
        sleep(1000);
        while (true) {
            if (textMatches("Polygon#").exists()) {
                break;
            } else {
                app.startActivity({
                    packageName: "com.evermorelabs.polygonsharp",
                    className: "com.evermorelabs.polygonsharp.LoginActivity",
                });
            }
            app.launchPackage("com.evermorelabs.polygonsharp");
            sleep(1000);

        }

        if (textMatches("LOGIN").exists()) {
            textMatches("LOGIN").findOne().click();
        }
        sleep(500);
        id("button_stop").findOne().click();
        sleep(500);
        id("button_start").findOne().click();
        if (storage.get("Partaking")) {
            textMatches("Pokémon GO").findOne()
            sleep(1000);
            textMatches("Pokémon GO").findOne().clickCenter();
            sleep(500);
            while (true) {
                if (textMatches("Pokémon GO").exists()) {
                    textMatches("Pokémon GO").findOne().clickCenter();
                } else {
                    break;
                }
                sleep(500);
            }

        }
        log("等待游戏出现");
        sleep(5000);
        if (等待游戏出现()) {
            break;
        }
    }
    log("3秒后拉远视角");
    sleep(3000);
    拉远视角();
    // sleep(1000);
}

function guolu(obj) {
    let getwb = ui.wb1.attr("text");
    let mText = getwb.split(",");
    if (mText.indexOf(obj[storage.get("j")].number) != -1) {
        return true;
    }
}

function ent() {
    Date.prototype.Format = function(fmt) {
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "H+": this.getHours() - 1, //小时
            "m+": this.getMinutes() + 1, //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            S: this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(
                RegExp.$1,
                (this.getFullYear() + "").substr(4 - RegExp.$1.length)
            );
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(
                    RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
                );
        return fmt;
    };
    var a = new Date().Format("yyyy/MM/dd HH:mm:ss");
    //log(a)
    return (new Date(a)).getTime() / 1000;
}



//申请截图权限
function ImgAuthority() {
    let end = threads.start(function() {
        while (true) {
            try {
                let Nodeclick = textMatches(/(允许|立即开始|同意)/).findOnce();
                if (Nodeclick) {
                    Nodeclick.click();
                }
            } catch (error) {
                console.error(error);
            }
            sleep(100);
        }
    });
    end.waitFor();
    if (!requestScreenCapture()) {
        end.interrupt();
        toastLog("请求截图失败");
        exit();
        return false;
    } else {
        end.interrupt();
        return true;
    }
}

function 判断闪光是否存在() {
    var img = captureScreen();
    var templs = images.read("./images/闪光.png");
    var templs1 = images.read("./images/闪光1.png");
    let x = device.width / 1080;
    let y = device.height / 2408;
    let templ = images.scale(templs, x, y);
    let templ1 = images.scale(templs1, x, y);

    let p = findImage(img, templ);
    let p1 = findImage(img, templ1);
    if (p || p1) {
        if (typeof templs != "undefined") {
            templs.recycle();
        }
        if (typeof templs1 != "undefined") {
            templs1.recycle();
        }
        if (typeof templ != "undefined") {
            templ.recycle();
        }
        if (typeof templ1 != "undefined") {
            templ1.recycle();
        }
        return true;
    } else {
        if (typeof templs != "undefined") {
            templs.recycle();
        }
        if (typeof templs1 != "undefined") {
            templs1.recycle();
        }
        if (typeof templ != "undefined") {
            templ.recycle();
        }
        if (typeof templ1 != "undefined") {
            templ1.recycle();
        }
        return false;
    }
    if (typeof templs != "undefined") {
        templs.recycle();
    }
    if (typeof templs1 != "undefined") {
        templs1.recycle();
    }
    if (typeof templ != "undefined") {
        templ.recycle();
    }
    if (typeof templ1 != "undefined") {
        templ1.recycle();
    }
}



function 等待游戏出现() {
    const timeout = "30000";
    const startTime = new Date().getTime();
    while (true) {
        var img = captureScreen();
        var templ = images.read("./images/球.png");
        let p = findImage(img, templ, {
            threshold: 0.8,
        });
        if (p) {
            log("游戏已打开");
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            return true;
            //break;
        }
        if (typeof templ != "undefined") {
            templ.recycle();
        }
        if (new Date().getTime() - startTime > timeout) {
            return false;
        }
    }
}

//自动捕获功能
function catchPokemon() {
    bx = device.width / 2;
    by = device.height - 200;
    ty = device.height / 3;
    swipe(bx, by, bx, ty, 300);
}

function 自动捕捉() {
    while (true) {
        sleep(1000);
        catchPokemon();
        sleep(5000);
        let r = mlkit.findText(/\/|%|AR+/, 1000, [0, StatusBarHeight, device.width, device.height]);
        if (!r.length) {
            log("怪物页面不存在,停止自动捕捉");
            break;
        }
    }
}

//拉远视角
function 拉远视角() {
    gestures([500, [device.width / 2, device.height / 6],
        [device.width / 2, device.height / 2]
    ], [500, [device.width / 2, device.height / 3 * 2],
        [device.width / 2, device.height / 2]
    ]);
}

function 点击中心点() {
    for (var i = 0; i < 100; i++) {
        let xy = storage.get("zhong");
        let setxy = storage.get("Offset");
        press(xy.split(",")[0], xy.split(",")[1], random(50, 100));
        sleep(250);
        press(xy.split(",")[0], xy.split(",")[1] - setxy, random(50, 100));
        sleep(250);
        press(xy.split(",")[0], xy.split(",")[1] + setxy, random(50, 100));
        sleep(250);
        press(xy.split(",")[0] - setxy, xy.split(",")[1], random(50, 100));
        sleep(250);
        press(xy.split(",")[0] + setxy, xy.split(",")[1], random(50, 100));
        log("点击中心点牌子" + storage.get("zhong"));
        sleep(2000);
        //判断精灵是否存在
        let r = mlkit.findText(/AR+|\/|%/, 1000, [0, StatusBarHeight, device.width, device.height]);
        if (r.length) {
            break;
        }
    }
}

function 获取坐标() {
    var arr = files.read("/sdcard/list.json");
    var data = JSON.parse(arr);
    return data;
}

function Joy传送(coord) {
    while (true) {
        sleep(1000);
        var img = captureScreen();
        var templl = images.read("./images/传送.png");
        var templ11 = images.read("./images/定位.png");
        var templ2 = images.read("./images/定位1.png");
        var templ3 = images.read("./images/定位2.png");
        var templ4 = images.read("./images/传送1.png");
        let x = device.width / 1080;
        let y = device.height / 2408;
        let templ = images.scale(templl, x, y);
        let templ1 = images.scale(templ11, x, y);

        let p = findImage(img, templ);
        let p1 = findImage(img, templ1);
        let p2 = findImage(img, templ2);
        let p3 = findImage(img, templ3);
        let p4 = findImage(img, templ4);
        if (p) {
            click(p.x + templ.getWidth() / 2, p.y + templ.getHeight() / 2);
            sleep(500)
            textMatches("传送").findOne(1000)
            setText(coord);
            //粘贴
            //id("paste_button").findOne().click();
            sleep(500)
            //传送
            id("teleport_button").findOne().click();
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templ2 != "undefined") {
                templ2.recycle();
            }
            if (typeof templ3 != "undefined") {
                templ3.recycle();
            }
            if (typeof templ4 != "undefined") {
                templ4.recycle();
            }
            break;
        } else if (p4) {
            click(p4.x + templ4.getWidth() / 2, p4.y + templ4.getHeight() / 2);
            sleep(500);
            textMatches("传送").findOne(1000)
            setText(coord);
            //粘贴
            // id("paste_button").findOne().click();
            sleep(500);
            //传送
            id("teleport_button").findOne().click();
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templ2 != "undefined") {
                templ2.recycle();
            }
            if (typeof templ3 != "undefined") {
                templ3.recycle();
            }
            if (typeof templ4 != "undefined") {
                templ4.recycle();
            }
            break;
        } else if (p1) {
            click(p1.x + templ1.getWidth() / 2, p1.y + templ1.getHeight() / 2);
            sleep(500);
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templ2 != "undefined") {
                templ2.recycle();
            }
            if (typeof templ3 != "undefined") {
                templ3.recycle();
            }
            if (typeof templ4 != "undefined") {
                templ4.recycle();
            }
        } else if (p2) {
            click(p2.x + templ2.getWidth() / 2, p2.y + templ2.getHeight() / 2);
            sleep(500);
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templ2 != "undefined") {
                templ2.recycle();
            }
            if (typeof templ3 != "undefined") {
                templ3.recycle();
            }
            if (typeof templ4 != "undefined") {
                templ4.recycle();
            }
        } else if (p3) {
            click(p3.x + templ3.getWidth() / 2, p3.y + templ3.getHeight() / 2);
            sleep(500);
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templ2 != "undefined") {
                templ2.recycle();
            }
            if (typeof templ3 != "undefined") {
                templ3.recycle();
            }
            if (typeof templ4 != "undefined") {
                templ4.recycle();
            }
        } else {
            log("未找到传送定位图片");
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templ2 != "undefined") {
                templ2.recycle();
            }
            if (typeof templ3 != "undefined") {
                templ3.recycle();
            }
            if (typeof templ4 != "undefined") {
                templ4.recycle();
            }
        }
        if (typeof templ != "undefined") {
            templ.recycle();
        }
        if (typeof templ1 != "undefined") {
            templ1.recycle();
        }
        if (typeof templ2 != "undefined") {
            templ2.recycle();
        }
        if (typeof templ3 != "undefined") {
            templ3.recycle();
        }
        if (typeof templ4 != "undefined") {
            templ4.recycle();
        }
    }
}






function 请求数据() {
    // threads.start(function() {
    var url = "https://moonani.com/PokeList/index.php";
    ret = http.get(url, {
        headers: {
            "Content-Type": "text/html; charset=UTF-8",
            "User-Agent": "Mozilla/5.0 (Linux; Android 6.0.1; OPPO R9s Plus Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36"
        }
    });
    files.write("/sdcard/百闪pol/a.html", ret.body.string());
    // a = ret.body.string()
    var a = files.read("/sdcard/百闪pol/a.html");
    // 坐标
    var b = a.match(/data-clipboard-text="(.*?)">/g);
    //图片
    var bb = a.match(/<td><img style="width:32px;height:32px" src="(.*?)"\/>/g);
    //title
    var cc = a.match(/<td><img style="width:32px;height:32px" src="https:\/\/twpkinfo.com\/images\/poke1\/(.*?)<\/td>/g);
    //国旗
    var dd = a.match(/<td><img style="width:22px;height:14px" src="(.*?)"\/>/g);
    //结束时间
    var ee = a.match(/<td>(.*?)<\/td>\n\t\t\t\t<td><img style="width:22px;height:14px"/g);
    //CP
    var ff = a.match(/<\/button><\/td>\n\t\t\t\t<td><b>\d+<\/b><\/td>/g);
    //IV
    var gg = a.match(/<td><b style="color:red">(.*?)<\/b><\/td>/g);
    //Level
    var hh = a.match(/<\/b><\/td>\n\t\t\t\t<td><b>(.*?)<\/b><\/td>/g);
    //闪光
    //https://moonani.com/PokeList/images/shiny.svg
    var sg = a.match(/%<\/b><\/td>\t\t\n\t\t\t\t<td>(.*?)<\/td>/g);
    var gs = a.match(/<tr>\n\t\t\t\t<td>(.*?)<\/td>/g);
    //编号
    var num = a.match(/<td>(\d+)<\/td>\n\t\t\t\t<td><button/g);

    var arr = []
    for (var i = 0; i < b.length; i++) {
        //坐标
        var c = TakeCenter(b[i], 'data-clipboard-text="', '">');
        //img
        var ct = TakeCenter(bb[i], '<td><img style="width:32px;height:32px" src="', '"/>');
        //title
        var ci = TakeCenter(cc[i], 'png"/>', '<');
        var arr1 = ci.replace(/&#9792;/g, '♀');
        var arr2 = arr1.replace(/&#9794;/g, '♂');
        var title = arr2.replace(/ <img style="width:16px/g, '');
        //国旗
        var gq = TakeCenter(dd[i], 'src="', '"/>');
        var country = gq.replace(/https:\/\/cdn.ip2location.com\/assets\/img\/flags\/.png/g, 'https://cdn.ip2location.com/assets/img/flags/au.png');
        //结束时间
        var EndTime = TakeCenter(ee[i], '>', '<');
        //CP
        var cp = TakeCenter(ff[i], '<b>', '</b>');
        //IV
        var iv = TakeCenter(gg[i], '">', '</b>');
        //Level
        var Level = TakeCenter(hh[i], '</b></td>\n\t\t\t\t<td><b>', '</b></td>');

        //闪光
        var Star = TakeCenter(sg[i], '<td>', '</td>');
        var Star1 = Star.replace(/Yes/g, 'https://www.268608.com/imgs/2022/08/24/6276ea8af66f9ac7.png');
        var Shiny = Star1.replace(/No/g, 'https://cdn.ip2location.com/assets/img/flags/.png');
        var id = TakeCenter(gs[i], "<td>", "</td>")
        var number = TakeCenter(num[i], "<td>", "</td>");
        arr.push({
            id: id,
            Coords: c,
            title: title,
            img: ct,
            country: country,
            EndTime: EndTime,
            cp: cp,
            iv: iv,
            Level: Level,
            Shiny: Shiny,
            Star: Star,
            number: number
        });
    }
    arrs = [];
    for (var j = 0; j < arr.length; j++) {
        if (arr[j].Star.indexOf("Yes") != -1) {
            arrs.push(arr[j])
        }
    }
    storage.put("nums", arrs.length);
    storage.put("j", 0);
    files.write("/sdcard/百闪pol/list.json", JSON.stringify(arrs));

    // files.write("/sdcard/百闪pol/list.json", JSON.stringify(arr));

    //}).join();
}

function 请求数据1(str) {
    while (true) {
        // threads.start(function() {
        var url = "https://moonani.com/PokeList/index.php";
        ret = http.get(url, {
            headers: {
                "Content-Type": "text/html; charset=UTF-8",
                "User-Agent": "Mozilla/5.0 (Linux; Android 6.0.1; OPPO R9s Plus Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36"
            }
        });
        files.write("/sdcard/百闪pol/a.html", ret.body.string());
        // a = ret.body.string()
        var a = files.read("/sdcard/百闪pol/a.html");
        // 坐标
        var b = a.match(/data-clipboard-text="(.*?)">/g);
        //图片
        var bb = a.match(/<td><img style="width:32px;height:32px" src="(.*?)"\/>/g);
        //title
        var cc = a.match(/<td><img style="width:32px;height:32px" src="https:\/\/twpkinfo.com\/images\/poke1\/(.*?)<\/td>/g);
        //国旗
        var dd = a.match(/<td><img style="width:22px;height:14px" src="(.*?)"\/>/g);
        //结束时间
        var ee = a.match(/<td>(.*?)<\/td>\n\t\t\t\t<td><img style="width:22px;height:14px"/g);
        //CP
        var ff = a.match(/<\/button><\/td>\n\t\t\t\t<td><b>\d+<\/b><\/td>/g);
        //IV
        var gg = a.match(/<td><b style="color:red">(.*?)<\/b><\/td>/g);
        //Level
        var hh = a.match(/<\/b><\/td>\n\t\t\t\t<td><b>(.*?)<\/b><\/td>/g);
        //闪光
        //https://moonani.com/PokeList/images/shiny.svg
        var sg = a.match(/%<\/b><\/td>\t\t\n\t\t\t\t<td>(.*?)<\/td>/g);
        var gs = a.match(/<tr>\n\t\t\t\t<td>(.*?)<\/td>/g);
        //编号
        var num = a.match(/<td>(\d+)<\/td>\n\t\t\t\t<td><button/g);

        var arr = []
        for (var i = 0; i < b.length; i++) {
            //坐标
            var c = TakeCenter(b[i], 'data-clipboard-text="', '">');
            //img
            var ct = TakeCenter(bb[i], '<td><img style="width:32px;height:32px" src="', '"/>');
            //title
            var ci = TakeCenter(cc[i], 'png"/>', '<');
            var arr1 = ci.replace(/&#9792;/g, '♀');
            var arr2 = arr1.replace(/&#9794;/g, '♂');
            var title = arr2.replace(/ <img style="width:16px/g, '');
            //国旗
            var gq = TakeCenter(dd[i], 'src="', '"/>');
            var country = gq.replace(/https:\/\/cdn.ip2location.com\/assets\/img\/flags\/.png/g, 'https://cdn.ip2location.com/assets/img/flags/au.png');
            //结束时间
            var EndTime = TakeCenter(ee[i], '>', '<');
            //CP
            var cp = TakeCenter(ff[i], '<b>', '</b>');
            //IV
            var iv = TakeCenter(gg[i], '">', '</b>');
            //Level
            var Level = TakeCenter(hh[i], '</b></td>\n\t\t\t\t<td><b>', '</b></td>');

            //闪光
            var Star = TakeCenter(sg[i], '<td>', '</td>');
            var Star1 = Star.replace(/Yes/g, 'https://www.268608.com/imgs/2022/08/24/6276ea8af66f9ac7.png');
            var Shiny = Star1.replace(/No/g, 'https://cdn.ip2location.com/assets/img/flags/.png');
            var id = TakeCenter(gs[i], "<td>", "</td>")
            var number = TakeCenter(num[i], "<td>", "</td>");
            arr.push({
                id: id,
                Coords: c,
                title: title,
                img: ct,
                country: country,
                EndTime: EndTime,
                cp: cp,
                iv: iv,
                Level: Level,
                Shiny: Shiny,
                Star: Star,
                number: number
            });
        }
        arrs = [];
        for (var j = 0; j < arr.length; j++) {
            if (arr[j].Star.indexOf("Yes") != -1) {
                arrs.push(arr[j])
            }
        }

        strs = []
        for (var i1 = 0; i1 < arrs.length; i1++) {
            for (var j1 = 0; j1 < str.length; j1++) {
                if (arrs[i1].number.indexOf(str[j1]) != -1) {
                    strs.push(arrs[i1]);
                }
            }
        }
        if (strs.length) {
            storage.put("nums", strs.length);
            storage.put("j", 0);
            files.write("/sdcard/百闪pol/list.json", JSON.stringify(strs));
            break;
        } else {
            log("没有选择的精灵数据,30秒后重新请求");
            sleep(30 * 1000);
        }
    }
}

function rad(d) {
    return d * Math.PI / 180.0;
}
// 根据经纬度计算距离，参数分别为第一点的经度，纬度；第二点的经度，纬度
function getDistances(lng1, lat1, lng2, lat2) {
    var radLat1 = rad(lat1);
    var radLat2 = rad(lat2);
    var a = radLat1 - radLat2;
    var b = rad(lng1) - rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6371; // EARTH_RADIUS;
    // 输出为公里
    s = Math.round(s * 10000) / 10000;
    var distance = s;
    var distance_str = "";
    if (parseInt(distance) >= 1) {
        // distance_str = distance.toFixed(1) + "km";
        distance_str = distance.toFixed(2) + "km";
        //distance_str1 = distance.toFixed(2)*1000;
    } else {
        // distance_str = distance * 1000 + "m";
        distance_str = (distance * 1000).toFixed(2) + "m";
    }
    //小小修改，这里返回对象
    let objData = {
        distance: distance,
        distance_str: distance_str,
        // distance_strm: distance_str1
    }
    return objData
}

function TakeCenter(文本内容, 关键字A, 关键字B) {
    var str = 文本内容;
    var aPos = str.indexOf(关键字A);
    var bPos = str.indexOf(关键字B, aPos + 关键字A.length);
    var retstr = str.substr(aPos + 关键字A.length, 文本内容.length - (aPos + 关键字A.length) - (文本内容.length - bPos));
    return retstr;
}


// function GetTime() {
//     Date.prototype.Format = function(fmt) {
//         var o = {
//             "M+": this.getMonth() + 1, //月份
//             "d+": this.getDate(), //日
//             "H+": this.getHours() - 1, //小时
//             "m+": this.getMinutes(), //分
//             "s+": this.getSeconds(), //秒
//             "q+": Math.floor((this.getMonth() + 3) / 3), //季度
//             S: this.getMilliseconds() //毫秒
//         };
//         if (/(y+)/.test(fmt))
//             fmt = fmt.replace(
//                 RegExp.$1,
//                 (this.getFullYear() + "").substr(4 - RegExp.$1.length)
//             );
//         for (var k in o)
//             if (new RegExp("(" + k + ")").test(fmt))
//                 fmt = fmt.replace(
//                     RegExp.$1,
//                     RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
//                 );
//         return fmt;
//     };
//     var a = new Date().Format("yyyy-MM-dd HH:mm:ss");
//     return (this.nowtime = a);
// }

function FenBianLv() {
    let resources = context.getResources();
    let resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
    let height = resources.getDimensionPixelSize(resourceId);
    return height;
}



function LoadingDialog(text) {
    importClass(android.graphics.drawable.GradientDrawable);
    let view = ui.inflate(
        <vertical>
            <progressbar  layout_weight="1" gravity="center" />
            <text id="txt" textStyle="bold" textColor="#000000" gravity="center" />
        </vertical>, null, false);

    let dialog = dialogs.build({
        customView: view,
        //title: "发现新版本",
        titleColor: "#3087fe",
        type: "app",
        // view高度超过对话框时是否可滑动
        wrapInScrollView: true,
        // 按下按钮时是否自动结束对话框
        autoDismiss: false,
        cancelable: false
    });
    let dialogWindow = dialog.getWindow();
    setBackgroundRoundRounded(dialogWindow);
    view.txt.attr("text", text);
    dialog.show();
    return dialog;
}

function setBackgroundRoundRounded(view) {
    let gradientDrawable = new GradientDrawable();
    gradientDrawable.setShape(GradientDrawable.RECTANGLE);
    gradientDrawable.setColor(colors.parseColor("#ffffff"));
    gradientDrawable.setCornerRadius(30);
    view.setBackgroundDrawable(gradientDrawable);

}

function 判断紫色() {
    var img = captureScreen();
    var templs = images.read("./images/紫色头.png");
    var templs1 = images.read("./images/紫色头1.png");
    let x = device.width / 1080;
    let y = device.height / 2408;
    let templ = images.scale(templs, x, y);
    let templ1 = images.scale(templs1, x, y);
    let p = findImage(img, templ);
    let p1 = findImage(img, templ1);
    if (p) {
        log("紫色图片存在");
        var point = findColor(img, "#FF9D27AF", {
            //xy 宽高
            region: [p.x, p.y, 75, 75],
            threshold: 4
        });
        if (point) {
            log("紫色存在");
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templs != "undefined") {
                templs.recycle();
            }
            if (typeof templs1 != "undefined") {
                templs1.recycle();
            }
            return true;
        } else {
            log("紫色不存在")
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templs != "undefined") {
                templs.recycle();
            }
            if (typeof templs1 != "undefined") {
                templs1.recycle();
            }
            return false;
        }
        if (typeof templ != "undefined") {
            templ.recycle();
        }
        if (typeof templ1 != "undefined") {
            templ1.recycle();
        }
        if (typeof templs != "undefined") {
            templs.recycle();
        }
        if (typeof templs1 != "undefined") {
            templs1.recycle();
        }

    } else if (p1) {
        log("紫色图片存在");
        var point = findColor(img, "#FF9D27AF", {
            //xy 宽高
            region: [p1.x, p1.y, 75, 75],
            threshold: 4
        });
        if (point) {
            log("紫色存在");
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templs != "undefined") {
                templs.recycle();
            }
            if (typeof templs1 != "undefined") {
                templs1.recycle();
            }
            return true;
        } else {
            log("紫色不存在")
            if (typeof templ != "undefined") {
                templ.recycle();
            }
            if (typeof templ1 != "undefined") {
                templ1.recycle();
            }
            if (typeof templs != "undefined") {
                templs.recycle();
            }
            if (typeof templs1 != "undefined") {
                templs1.recycle();
            }
            return false;
        }
        if (typeof templ != "undefined") {
            templ.recycle();
        }
        if (typeof templ1 != "undefined") {
            templ1.recycle();
        }
        if (typeof templs != "undefined") {
            templs.recycle();
        }
        if (typeof templs1 != "undefined") {
            templs1.recycle();
        }

    } else {
        log("紫色图片不存在");
        if (typeof templ != "undefined") {
            templ.recycle();
        }
        if (typeof templ1 != "undefined") {
            templ1.recycle();
        }
        if (typeof templs != "undefined") {
            templs.recycle();
        }
        if (typeof templs1 != "undefined") {
            templs1.recycle();
        }
    }
    if (typeof templ != "undefined") {
        templ.recycle();
    }
    if (typeof templ1 != "undefined") {
        templ1.recycle();
    }
    if (typeof templs != "undefined") {
        templs.recycle();
    }
    if (typeof templs1 != "undefined") {
        templs1.recycle();
    }

}